/**
 * 
 */
package info.niwota.fwrite;

import info.niwota.fwrite.imglist.MultiSelectImageActivity;
import info.niwota.webapp.InstallHotwebActivity;
import info.niwota.webapp.WebIntents;

import java.io.File;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;

/**
 * @author qiangli
 *
 */
public class NotesActivity extends NoteListActivity {
	
	private static final String TAG = "NotesActivity";
	

	private static final int DIALOG_ACTIONS = 2;

	private static final int DIALOG_HELP = 1;

	private static final String HELP_URI = "file:///android_asset/index.html";

	//private static final int RC_LIST_PEER = 6;

	private static final int RC_PICK_PEER = 4;
	
	private static final int RC_SETTINGS = 2;
	
	private static final int RC_SWITCH_SESSION = 5;
	
	private static final int RC_VIEW_NOTE = 21;
	
	private static final int RC_EDIT_NOTE = 22;
	
	private static final int RC_COMPOSE = 23;
	
	private static final int RC_CHAT = 24;

	private Dialog createActionsDialog() {
		return MenuDialogs.createMenuDialog(this, R.string.action_menu,
				new MenuCallback() {
					public void perform(MenuInfo mi) {
						switch (mi.getId()) {
						case R.string.action_top:
							doShowTop();
							break;
						case R.string.action_compose:
							doCompose();
							break;
						case R.string.action_sessions:
							doListSessions();
							break;
						case R.string.action_peers:
							doPickPeer();
							break;
						case R.string.action_archive:
							doViewArchive();
							break;
						}
					}
				});
	}

	private Dialog createHelpDialog() {
		LayoutInflater f = LayoutInflater.from(this);
		final View v = f.inflate(R.layout.webdia, null);

		Dialog d = new Dialog(this);
		LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		d.requestWindowFeature(Window.FEATURE_LEFT_ICON);
		d.setContentView(v, lp);
		d.setTitle(R.string.help_label);
		d.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.ic_dialog_menu_generic);
		return d;
	}

	private void doActions() {
		showDialog(DIALOG_ACTIONS);
	}

	private void doChat(String peer, int status) {
		try {
			Intent i = new Intent(this, ChatActivity.class);
			startActivity(i);
		} catch (Exception e) {
			showError(e);
		}
	}
	
	
//	private void doListPeer() {
//		try {
//			if (InstallHotwebActivity.ensure(this)) {
//				Intent i = new Intent();
//				i.setClassName("info.niwota.web",
//						"info.niwota.web.user.UserListActivity");
//				startActivityForResult(i, RC_LIST_PEER);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	@Override
	protected void doEditNote(Document doc) {
		if (Debug.DEBUG) {
			Log.d(TAG, "doEditNote doc: " + doc);
		}
		
		super.doEditNote(doc);
		
		try {
			Intent i = new Intent(this, EditNoteActivity.class);
			i.putExtra(EditNoteActivity.EXTRA_DOC, doc.getPath());
			startActivityForResult(i, RC_EDIT_NOTE);
		} catch (Exception e) {
			showError(e);
		}
	}

	@Override
	protected void doViewNote(Document doc) {
		super.doViewNote(doc);
		
		try {
			Intent i = new Intent(this, ViewNoteActivity.class);
			startActivityForResult(i, RC_VIEW_NOTE);
		} catch (Exception e) {
			showError(e);
		}
	}

	private void doCompose() {
		try {
			Intent i = new Intent(this, ComposeActivity.class);
			startActivity(i);
		} catch (Exception e) {
			showError(e);
		}
	}

	/**
	 * remove notification and quit
	 */
	protected void doFinish() {
		if (Debug.DEBUG) {
			Log.d(TAG, "doFinish");
		}
		StatusHelper.removeNotification(this);
		//
		doQuit();
	}

	private void doHelp() {
		showDialog(DIALOG_HELP);
	}
	
	private void doListSessions() {
		Intent i = new Intent(this, SessionListActivity.class);
		startActivityForResult(i, RC_SWITCH_SESSION);
	}
	
	private void doPeerPicked(Intent data) {
		if (Debug.DEBUG) {
			Log.d(TAG, "data extras: "+ data.getExtras());
		}
		String peer = data.getStringExtra(WebIntents.EXTRA_PEER);
		int status = data.getIntExtra(WebIntents.EXTRA_STATUS, 0);
		
		SessionManager.ensureSession(peer);
		
		doChat(peer, status);
	}

	private void doPickPeer() {
		try {
			if (InstallHotwebActivity.ensure(this)) {
				Intent i = new Intent();
				i.setClassName("info.niwota.web",
						"info.niwota.web.user.PickUserActivity");
				startActivityForResult(i, RC_PICK_PEER);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doQuit() {
		if (Debug.DEBUG) {
			Log.d(TAG, "doQuit");
		}
		//
		finish();
	}

	private void doSessionPicked(Intent data) {
		if (Debug.DEBUG) {
			Log.d(TAG, "data extras: "+ data.getExtras());
		}
		SessionInfo si = (SessionInfo) data.getSerializableExtra(SessionListActivity.SESSION_INFO);
		
		String peer = si.peer;
		int status = si.status;

		doChat(peer, status);
	}

	private void doSettings() {
		try {
			Intent i = new Intent(this, SettingsActivity.class);
			startActivityForResult(i, RC_SETTINGS);
		} catch (Exception e) {
			// e.printStackTrace();
		}
	}

	private void doViewArchive() {
		try {
			Intent i = new Intent(this, MultiSelectImageActivity.class);
			i.setAction(Intent.ACTION_VIEW);
			File dir = SDCard.getNoteDir();
			Uri data = Uri.parse(dir.toURI().toString());
			i.setData(data);
			startActivity(i);
		} catch (Exception e) {
			showError(e);
		}
	}

	@Override
	protected void initRes() {
		super.initRes();
		
		mActionSortBy.setVisibility(View.GONE);
		mActionSortBy.setEnabled(false);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (Debug.DEBUG) {
			Log.d(TAG, "onActivityResult requestCode: " + requestCode
					+ " resultCode: " + resultCode + " == " + RESULT_OK
					+ " data: " + data);
		}
		if (resultCode == RESULT_CANCELED) {
			return;
		}
		try {
			switch (requestCode) {
			case RC_SETTINGS:
				final Context ctx = this;
				if (Preferences.enableStatusbar(ctx)) {
					StatusHelper.addNotification(ctx);
				} else {
					StatusHelper.removeNotification(ctx);
				}
				//mLinesize = Preferences.getEditLinesize(ctx);
				//mAutoSpace = Preferences.enableAutoSpace(ctx);
				//
				break;
			case RC_PICK_PEER:
				doPeerPicked(data);
				break;
			case RC_SWITCH_SESSION:
				doSessionPicked(data);
				break;
			default:
			}
		} catch (Exception e) {
			showError(e);
		}
	}


	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.menu_actions:
			doActions();
			return;
		}
		super.onClick(v);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		super.onCreate(savedInstanceState);
		
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		//
		doShowTop();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_HELP:
			return createHelpDialog();
		case DIALOG_ACTIONS:
			return createActionsDialog();
		default:
		}
		
		return super.onCreateDialog(id);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.write_options, menu);
		//
		return true;
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (Debug.DEBUG) {
			Log.d(TAG, "onOptionsItemSelected: " + item);
		}

		int id = item.getItemId();
		switch (id) {
		case R.id.write_help_opt_menu_id:
			doHelp();
			return true;
		case R.id.write_settings_opt_menu_id:
			doSettings();
			return true;
		case R.id.write_quit_opt_menu_id:
			doFinish();
			return true;
		case R.id.write_peers_opt_menu_id:
			doPickPeer();
			return true;
		case R.id.write_compose_opt_menu_id:
			doCompose();
			return true;
		case R.id.write_top_opt_menu_id:
			doShowTop();
			return true;
		default:
		}
		
		return false;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		switch(id) {
			case DIALOG_HELP:
			WebView wv = (WebView) dialog.findViewById(R.id.webview);
			wv.loadUrl(HELP_URI);
			wv.setFocusable(true);
			wv.setFocusableInTouchMode(true);
			break;
		} 
	}

	@Override
	protected void doTitleAction() {
		doNaviBC();
	}

	@Override
	protected void doMenuAction() {
		showDialog(DIALOG_ACTIONS);
	}

}
